package com.iflytek.autofly.setting.biz.car;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.iflytek.autofly.carinfoservice.aidl.RRMMod;
import com.iflytek.autofly.carinfoservice.util.CarinfoContents;
import com.iflytek.autofly.carinfoservice.util.CarinfoListener;
import com.iflytek.autofly.carinfoservice.util.CarinfoManager;
import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.biz.Notice;
import com.iflytek.autofly.setting.biz.base.BaseFragment;
import com.iflytek.autofly.setting.biz.base.CommonRadioButtonBean;
import com.iflytek.autofly.setting.biz.base.CommonRadioGroupAdpt;
import com.iflytek.autofly.setting.biz.system.FlyTimePickerDialog;
import com.iflytek.autofly.setting.widget.InnerListView;
import com.iflytek.autofly.setting.widget.LoadingAnimView;
import com.iflytek.autofly.utils.FlyLog;
import com.iflytek.sunflower.FlowerCollector;

import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <b>Description: </b>声音设置的fragment<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>JunLuan@iflytek.com</td>
 * <td>2015年10月14日</td>
 * <td>上午11:34:14</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author JunLuan@iflytek.com
 */
public class CarFragment extends BaseFragment {
    protected static final String TAG = "CarFragment";
    private static final String[] CMD = {};

    private static final int TIME_WAIT_TO_DIALOG = 500;
    private static final int TIME_WAIT_CAN_TIMEOUT_AFTER_DIALOG = 1500;
    private static final int TIME_WAIT_CAN_TIMEOUT = 2000;

    private static final int MSG_SHOW_WAITING_DIALOG = 1;
    private static final int MSG_CAN_SET_TIMEOUT = 2;

    private static final String ACTION_SYNC_PANEL_TIME = "autofly.intent.action.SYNC_PANEL_TIME";

    private AtomicInteger mServiceReady = new AtomicInteger(0);
    private InnerListView mSecurityLv;
    //    private InnerListView mLangLv;
    private CarinfoManager mCarinfoManager;
    private ToggleButton mEbWarningSwitch;
    private ToggleButton mSaLightSwitch;
    private TextView mTimeTv;

    private boolean mSaLightState;
    //    private int mLang;
    private int mSecurity;
    private int mTime;
    private CarinfoListener mCarinfoListener;
    private TextView mSecurityTv;
//    private TextView mLangTv;

    private Handler mHandler = new H();

    private class H extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SHOW_WAITING_DIALOG:
                    int position = msg.arg1;
                    LoadingAnimView.show(getContext(), getString(R.string.car_sys_setting));
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_CAN_SET_TIMEOUT, position, 0),
                            TIME_WAIT_CAN_TIMEOUT_AFTER_DIALOG);
                    break;
                case MSG_CAN_SET_TIMEOUT:
                    position = msg.arg1;
                    if (position != -1) {
                        mSecurityLv.setItemStatus(position, 0);
                    }
                    LoadingAnimView.hide();
                    Notice.getInstatnce().show(getString(R.string.car_sys_error), true);
                    renew();
                    break;
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        init(view);
        return view;
    }

    @Override
    public void onDestroy() {
        mCarinfoManager.unregisterListener(mCarinfoListener);
        mCarinfoManager = null;
        mServiceReady.set(0);
        super.onDestroy();
    }

    private void init(View v) {
        addUnit(R.layout.carebwarning);
        addHiddenUnit(R.layout.carsalighting);
        addUnit(R.layout.carsecuritytips, R.layout.carsecuritytips_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mSecurityTv.setVisibility(View.GONE);
                } else {
                    mSecurityTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
//        addUnit(R.layout.carpanellang, R.layout.carpanellang_sub, new OnExpandChangeListener() {
//            @Override
//            public void onExpandChanged(boolean isExpanded) {
//                if (isExpanded) {
//                    mLangTv.setVisibility(View.GONE);
//                } else {
//                    mLangTv.setVisibility(View.VISIBLE);
//                }
//            }
//        }, null);
        addUnit(R.layout.carpaneltime);
        addHiddenUnit(R.layout.aboutsystem);

        mEbWarningSwitch = (ToggleButton) v.findViewById(R.id.car_ebwarning_switch_tbn);
        mEbWarningSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            }
        });
        mEbWarningSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isChecked = mEbWarningSwitch.isChecked();            
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.car) + "-" + getString(R.string.car_emergency_braking_warning), "" + isChecked);
                RRMMod mode = new RRMMod();
                mode.setUrgencyBrakeActivehazardLamp(isChecked ? 1 : 0);
                mCarinfoManager.setRRMMod(mode, CarinfoContents.RRMModContents.RRM_Hazard);
                mEbWarningSwitch.setEnabled(false);
                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_CAN_SET_TIMEOUT, -1, 0), TIME_WAIT_CAN_TIMEOUT);
            }
        });
        mSaLightSwitch = (ToggleButton) v.findViewById(R.id.car_salighting_switch_tbn);
        mSaLightSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked != mSaLightState) {
                    mSaLightState = isChecked;
                    RRMMod mode = new RRMMod();
                    mode.setAidTurningIllumination(isChecked ? 1 : 0);
                    mCarinfoManager.setRRMMod(mode, CarinfoContents.RRMModContents.RRM_Turnlight);
                }
            }
        });
        initSecurityView(v);
        initLangView(v);
        RelativeLayout timeRl = (RelativeLayout) v.findViewById(R.id.car_panel_time_rl);
        timeRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.car) + "-" + getString(R.string.car_panel_time));
                final Calendar calendar = Calendar.getInstance();
                Dialog d = new FlyTimePickerDialog(getActivity(),
                        new FlyTimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(com.iflytek.autofly.flypicker.TimePicker view, int hourOfDay, int minute) {
                                mTime = hourOfDay * 60 + minute;
                                RRMMod mode = new RRMMod();
                                mode.setTimeHour(hourOfDay);
                                mode.setTimeMinute(minute);
                                mCarinfoManager.setRRMMod(mode, CarinfoContents.RRMModContents.RRM_TIME);
                                // Notify settingassist to sync panel time every minute.
                                Intent intent = new Intent(ACTION_SYNC_PANEL_TIME);
                                getActivity().sendBroadcast(intent);
//                                mTimeTv.setText(String.format("%02d:%02d", hourOfDay, minute));
                                mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHOW_WAITING_DIALOG, -1, 0), TIME_WAIT_TO_DIALOG);
                            }
                        },
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE),
                        true);
                d.show();
            }
        });

        mTimeTv = (TextView) v.findViewById(R.id.car_panel_time_value_tv);

        mCarinfoListener = new CarinfoListener() {
            @Override
            public void onCarInfoChange(final int modType, final int valueType, final float value) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (modType) {
                            case CarinfoContents.RRMModContents.MAINID:
                                // 行车电脑
                                switch (valueType) {
                                    case CarinfoContents.RRMModContents.RRM_Hazard:
                                        // 紧急制动警示
                                        int type = (int) value;
                                        mEbWarningSwitch.setEnabled(true);
                                        if (type == 0 || type == 1) {
                                            boolean ebWarningState = type == 1;
                                            if (mEbWarningSwitch.isChecked() == ebWarningState) {
                                                mHandler.removeMessages(MSG_CAN_SET_TIMEOUT);
                                            }
                                        } else {
                                            FlyLog.e(TAG, "Invalid RRM_Hazard " + type);
                                        }
                                        break;
                                    case CarinfoContents.RRMModContents.RRM_LANGUAGE:
                                        // 语言
//                                        int lang = (int) value;
//                                        if (lang == 0 || lang == 1) {
//                                            mLang = lang;
//                                            mLangLv.setItemChecked(lang, true);
//                                            switch (lang) {
//                                                case 0:
//                                                    mLangTv.setText(getString(R.string.car_panel_language_sc));
//                                                    break;
//                                                case 1:
//                                                    mLangTv.setText(getString(R.string.car_panel_language_en));
//                                                    break;
//                                            }
//                                        } else {
//                                            FlyLog.e(TAG, "Invalid RRM_LANGUAGE " + lang);
//                                        }
                                        break;
                                    case CarinfoContents.RRMModContents.RRM_REMOTE:
                                        // 锁车提示
                                        int remote = remoteModeToIndex((int) value);
                                        if (remote >= 0 && remote <= 2) {
                                            if (remote != mSecurity) {
                                                mHandler.removeMessages(MSG_SHOW_WAITING_DIALOG);
                                                mHandler.removeMessages(MSG_CAN_SET_TIMEOUT);
                                                LoadingAnimView.hide();
                                                mSecurity = remote;
                                                mSecurityLv.setItemStatus(remote, 2);
                                                mSecurityLv.setItemChecked(remote, true);
                                                updateRemoteText(remote);
                                            }
                                        }
                                        break;
                                    case CarinfoContents.RRMModContents.RRM_Turnlight:
                                        // 转向辅助
                                        int light = (int) value;
                                        if (light == 0 || light == 1) {
                                            mSaLightState = light == 1;
                                            mSaLightSwitch.setChecked(mSaLightState);
                                        } else {
                                            FlyLog.e(TAG, "Invalid RRM_Turnlight " + light);
                                        }
                                        break;
                                    case CarinfoContents.RRMModContents.RRM_TIME:
                                        mHandler.removeMessages(MSG_SHOW_WAITING_DIALOG);
                                        mHandler.removeMessages(MSG_CAN_SET_TIMEOUT);
                                        LoadingAnimView.hide();
                                        mTime = (int) value;
                                        mTimeTv.setText(String.format("%02d:%02d", mTime / 60, mTime % 60));
                                        break;
                                }
                                break;
                        }
                    }
                });
            }


            @Override
            public void onServiceStatusChanged(int state) {
                switch (state) {
                    case CarinfoContents.AidlStatus.SERVICE_AIDL_BOUND:
                        FlyLog.d(TAG, "SERVICE_AIDL_BOUND");
                        renew();
                        break;
                    case CarinfoContents.AidlStatus.SERVICE_AIDL_BINDING:
                        break;
                    case CarinfoContents.AidlStatus.SERVICE_AIDL_NOT_BOUND:
                        FlyLog.e(TAG, "SERVICE_AIDL_NOT_BOUND");
                    default:
                        FlyLog.e(TAG, "unexpected state:" + state);
                }

            }
        };
        mCarinfoManager = CarinfoManager.registerListener(getActivity(), mCarinfoListener);
    }

    public void renew() {
        if (mServiceReady.incrementAndGet() < 3) {
            return;
        }

        RRMMod mode = mCarinfoManager.getRRMMod();

        if (mode == null) {
            FlyLog.e(TAG, "getRRMMod failed");
            return;
        }
        final boolean ebWarningState = mode.getUrgencyBrakeActivehazardLamp() == 1;
        mSaLightState = mode.getAidTurningIllumination() == 1;
        //mLang = mode.getLanguage();
        mSecurity = remoteModeToIndex(mode.getRemoteLockFeedback());
        mTime = mode.getTimeHour() * 60 + mode.getTimeMinute();
        FlyLog.d(TAG, "mEbWarningState=" + ebWarningState
                + ",mSaLightState=" + mSaLightState
                // + ",mLang=" + mLang
                + ",mSecurity=" + mSecurity
                + ",mTime=" + mTime);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mEbWarningSwitch.setChecked(ebWarningState);
                mEbWarningSwitch.setEnabled(true);
                mSaLightSwitch.setChecked(mSaLightState);
                updateRemoteText(mSecurity);
                mSecurityLv.setItemStatus(mSecurity, 2);
                mSecurityLv.setItemChecked(mSecurity, true);
                //mLangLv.setItemChecked(mLang, true);
                mTimeTv.setText(String.format("%02d:%02d", mTime / 60, mTime % 60));
            }
        });
    }

    private int remoteModeToIndex(int remote) {
        switch (remote) {
            case RRMMod.REMOTE_LAMP:
                return 1;
            case RRMMod.REMOTE_LAMPANDSPEEKER:
                return 0;
            case RRMMod.REMOTE_SPEEKER:
                return 2;
            default:
                FlyLog.e(TAG, "Invalid RRM_REMOTE " + remote);
        }
        return -1;
    }

    private void updateRemoteText(int remote) {
        switch (remote) {
            case 0:
                mSecurityTv.setText(getString(R.string.car_security_both));
                break;
            case 1:
                mSecurityTv.setText(getString(R.string.car_security_light));
                break;
            case 2:
                mSecurityTv.setText(getString(R.string.car_security_horn));
                break;
        }
    }

    @Override
    public void processCommandline(String cmd) {
    }

    @Override
    public String[] getCommands() {
        return CMD;
    }


    private void initSecurityView(View v) {
        mSecurityLv = (InnerListView) v.findViewById(R.id.car_security_tips_listview);
        mSecurityTv = (TextView) v.findViewById(R.id.car_security_tips_value_tv);
        CommonRadioGroupAdpt contentListAdpt = new CommonRadioGroupAdpt(getActivity());
        //contentListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.car_security_none), R.string.car_security_none));
        contentListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.car_security_both), R.string.car_security_both));
        contentListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.car_security_light), R.string.car_security_light));
        contentListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.car_security_horn), R.string.car_security_horn));
        mSecurityLv.setAdapter(contentListAdpt);
        mSecurityLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.car) + "-" + getString(R.string.car_security_tips), getString((int) id));
                if (position != mSecurity) {
//                    mSecurity = position;
                    RRMMod mode = new RRMMod();
                    mode.setRemoteLockFeedback(getRemoteAt(position));
                    mCarinfoManager.setRRMMod(mode, CarinfoContents.RRMModContents.RRM_REMOTE);
//                    mSecurityTv.setText(getString((int) id));
                    mSecurityLv.setItemStatus(position, 1);
                    mSecurityLv.setItemChecked(position, true);
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SHOW_WAITING_DIALOG, position, 0),
                            TIME_WAIT_TO_DIALOG);
                }
            }
        });

    }

    private int getRemoteAt(int index) {
        final int[] remote = {RRMMod.REMOTE_LAMPANDSPEEKER, RRMMod.REMOTE_LAMP, RRMMod.REMOTE_SPEEKER};

        if (index < 0 && index > remote.length) {
            return remote[0];
        }
        return remote[index];
    }


    private void initLangView(View v) {
//        mLangLv = (InnerListView) v.findViewById(R.id.car_panel_language_listview);
//        mLangTv = (TextView) v.findViewById(R.id.car_panel_language_value_tv);
//        CommonRadioGroupAdpt contentListAdpt = new CommonRadioGroupAdpt(getActivity());
//        contentListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.car_panel_language_sc), R.string.car_panel_language_sc));
//        contentListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.car_panel_language_en), R.string.car_panel_language_en));
//        mLangLv.setAdapter(contentListAdpt);
//        mLangLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (position != mLang) {
//                    mLang = position;
//                    RRMMod mode = new RRMMod();
//                    mode.setLanguage(mLang);
//                    mCarinfoManager.setRRMMod(mode, CarinfoContents.RRMModContents.RRM_LANGUAGE);
//                    mLangTv.setText(getString((int) id));
//                }
//            }
//        });
    }

}
